package com.czmc.smalldemo.app.main;


import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by MZone on 1/16/2017.
 */

public abstract class Utils {
    public void doDownload(final String url, final File file) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder().build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("LOGGER",e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //此处可以增加判断文件是否存在的逻辑

                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    long contentLen = response.body().contentLength();
                    long downloadLen = 0;
                    fos = new FileOutputStream(file);
                    long currentPercent = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        downloadLen += len;
                            if (downloadLen * 100 / contentLen - currentPercent >= 1) {
                                currentPercent = downloadLen * 100 / contentLen;
                            }
                        Log.e("LOGGER",currentPercent+"");

                    }
                    fos.flush();
                    fos.close();
                    is.close();
                    onDownLoadFinish();

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null) is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null) fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }
    private  String getFileName(String path) {
        int separatorIndex = path.lastIndexOf("/");
        return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
    }
    public abstract void onDownLoadFinish();

}
